<template>
  <el-dialog v-model="dialogVisible" width="400" :title="title" draggable appendToBody destroyOnClose lockScroll :closeOnClickModal="false">
    <el-form ref="elFormRef" v-loading="initLoading" :model="formData" :rules="rules" scrollToError statusIcon>
      <el-form-item label="父部门" labelWidth="6em" prop="dataScope">
        <el-tree-select
          v-model="formData.parentId"
          :data="props.deptList"
          :props="{
            label: 'deptName',
            children: 'children',
          }"
          valueKey="deptId"
          checkStrictly
          :renderAfterExpand="false"
          showCheckbox
        ></el-tree-select>
      </el-form-item>
      <el-form-item label="部门名称" prop="deptName" required labelWidth="6em">
        <el-input v-model="formData.deptName" placeholder="请输入部门名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="部门状态" labelWidth="6em" prop="status">
        <box-from-border>
          <el-radio-group v-model="formData.status">
            <el-radio label="启用" :value="0"></el-radio>
            <el-radio label="停用" :value="1"></el-radio>
          </el-radio-group>
        </box-from-border>
      </el-form-item>
      <el-form-item labelWidth="0em">
        <div style="width: 100%; padding-top: 20px">
          <el-button style="width: 100%" type="success" :loading="submitLoading" :disabled="submitLoading" :icon="IconPlus" @click="submit">保存</el-button>
        </div>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
  import IconPlus from '~icons/ep/plus';
  import type { FormInstance, FormRules } from 'element-plus';
  import { type DeptItem, addSysDeptListAxios, editSysDeptListAxios } from '@/api/permission-management';

  type $AddShowData = {
    type: 'add';
    /** 添加时的回调 */
    addCallBack: () => void;
  };
  type $EditShowData = {
    type: 'edit';
    /** 角色 */
    data: DeptItem;
    /** 编辑时的回调 */
    editCallBack: () => void;
  };
  interface DetpTreeNode<T> {
    deptId: string;
    parentId?: string;
    children?: DetpTreeNode<T>[];
    [key: string]: any;
  }
  type Props = {
    /** 部门列表 */
    deptList?: DetpTreeNode<DeptItem>[];
  };
  const props = withDefaults(defineProps<Props>(), {
    deptList: () => [],
  });
  let addCallBack: $AddShowData['addCallBack'] | undefined = undefined;
  let editCallBack: $EditShowData['editCallBack'] | undefined = undefined;
  const submitLoading = ref(false);
  const initLoading = ref(false);
  const atcion = ref('');
  const dialogVisible = ref(false);
  const elFormRef: Ref<FormInstance | null> = ref(null);
  const title: Ref<string> = ref('新增部门');
  const formData = ref<DeptItem>({
    parentId: '',
    deptId: '',
    deptName: '',
    status: 0,
  });

  const rules = computed<FormRules>(() => {
    const _rules: FormRules = {
      deptName: [{ required: true, type: 'string', message: '请输入部门名称', trigger: ['blur', 'change'] }],
    };
    return _rules;
  });

  /**
   * 显示
   */
  function show(data: $AddShowData | $EditShowData) {
    editCallBack = 'editCallBack' in data && typeof data.editCallBack === 'function' ? data.editCallBack : undefined;
    addCallBack = 'addCallBack' in data && typeof data.addCallBack === 'function' ? data.addCallBack : undefined;
    title.value = data.type === 'edit' ? '编辑部门' : '新增部门';
    dialogVisible.value = true;
    atcion.value = data.type;

    if (data.type === 'edit' && typeof data.data) {
      formData.value.parentId = data.data.parentId;
      formData.value.deptId = data.data.deptId;
      formData.value.deptName = data.data.deptName;
      formData.value.status = data.data.status;
    } else {
      formData.value.parentId = '';
      formData.value.deptId = '';
      formData.value.deptName = '';
      formData.value.status = 0;
    }
  }

  /**
   * 隐藏
   */
  function hide() {
    dialogVisible.value = false;
  }

  /** 提交 */
  async function submit() {
    try {
      await elFormRef.value?.validate();
    } catch (error) {
      ElToast.error('提交失败，请完善表单，-BD002');
      return;
    }
    try {
      if (atcion.value === 'edit') {
        await editSysDeptListAxios(formData.value);
        typeof editCallBack === 'function' && editCallBack();
      } else {
        await addSysDeptListAxios(formData.value);
        typeof addCallBack === 'function' && addCallBack();
      }
      ElToast.success('提交成功');
      hide();
    } catch (error) {
      ElToast.error(error.msg || '提交失败，-BD003');
    }
  }

  defineExpose({ show, hide });
</script>
